package com.perfma.xtest.cmd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public class JobExecutor {
    private static final Logger logger = LoggerFactory.getLogger(JobExecutor.class);

    // ---------------------- job thread repository ----------------------
    private static ConcurrentHashMap<Long, JobThread> JobThreadRepository = new ConcurrentHashMap<Long, JobThread>();

    private static JobExecutor jobExecutor = new JobExecutor();

    public static JobThread registJobThread(Long threadId) {
        JobThread newJobThread = new JobThread();
        newJobThread.start();
        JobThread oldJobThread = JobThreadRepository.put(threadId, newJobThread);
        logger.info(">>>>>>>>>>> 任务线程注册成功, 任务:{},当前任务线程池共有:{} 任务", threadId, JobThreadRepository.size());
        return newJobThread;
    }

    public static void removeJobThread(Long jobId, String removeOldReason) {
        JobThread oldJobThread = JobThreadRepository.remove(jobId);
        if (oldJobThread != null) {
            oldJobThread.toStop(removeOldReason);
            oldJobThread.interrupt();
        }
    }

    public static JobThread loadJobThread(Long jobId) {
        JobThread jobThread = JobThreadRepository.get(jobId);
        return jobThread;
    }

    public static ConcurrentHashMap<Long, JobThread> getJobThreadRepository() {
        return JobThreadRepository;
    }

    public static JobExecutor getJobExecutor() {
        return jobExecutor;
    }
}
